package com.ssyt.ec.exam.service;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.apache.commons.lang3.StringUtils;

import com.ssyt.ec.common.PageModel;
import com.ssyt.ec.common.util.DBUtil;
import com.ssyt.ec.common.util.FastjsonUtil;
import com.ssyt.ec.exam.entity.ExamPaperEntity;
import com.ssyt.ec.que.entity.QuestionEntity;
import com.ssyt.ec.sys.entity.CourseEntity;

public class ExamPaperService {
	/**
	 * 查询所属课程
	 * 
	 * @return
	 */
	public List<CourseEntity> listCourse() {
		String sql = "select * from sys_course where state=1";
		return DBUtil.executeQuery(CourseEntity.class, sql);
	}

	/**
	 * 查询试卷清单
	 * 
	 * @param sort
	 * @param order
	 * @param page
	 * @param rows
	 * @return
	 */
	public PageModel<ExamPaperEntity> listPaper(String sort, String order,
			int page, int rows) {
		StringBuilder sb = new StringBuilder();
		sb.append("SELECT qe.id,qe.name,qe.paper_url,qe.total_point,qe.pass_point,qe.total_minutes,qe.state ");
		sb.append(",co.name AS sys_course_name ");
		sb.append("FROM qes_exam_paper qe,sys_course co ");
		sb.append("WHERE qe.course_id = co.id ");
		sb.append("ORDER BY qe.id ");
		sb.append(" LIMIT ?, ? ");

		return DBUtil.executeQueryByPage(ExamPaperEntity.class, sb.toString(),
				(page - 1) * rows, rows);
	}

	public ExamPaperEntity getPaper(int id) {
		StringBuilder sb = new StringBuilder();
		sb.append("SELECT qe.course_id,qe.id, qe.name, qe.paper_url,qe.paper_type, co.name AS sys_course_name,qe.total_point,qe.pass_point,qe.total_minutes,qe.single_option_number,qe.single_option_each_point,qe.single_option_difficulty,qe.multi_option_number,qe.multi_option_each_point,qe.multi_option_difficulty,qe.judge_number,qe.judge_each_point,qe.judge_difficulty,qe.state, qe.memo ");
		sb.append(" FROM sys_course co,qes_exam_paper qe ");
		sb.append(" WHERE qe.id = ? and qe.course_id = co.id;");

		return DBUtil.getUniqueResult(ExamPaperEntity.class, sb.toString(), id);
	}

	/**
	 * 增加试卷信息
	 * 
	 * @param paramList
	 * @return
	 */
	public int addPaper(List<Object> paramList) {
		String Sql = "INSERT INTO `qes_exam_paper` "
				+ "(`name`, `paper_url`, `paper_type`, `course_id`, `total_point`, `pass_point`, "
				+ "`total_minutes`, `single_option_number`, `single_option_each_point`, `single_option_difficulty`, "
				+ "`multi_option_number`, `multi_option_each_point`, `multi_option_difficulty`, `judge_number`, "
				+ "`judge_each_point`, `judge_difficulty`, `opreate_user_id`, `opreate_time`, `state`, `memo`) "
				+ "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?,?, ?, ?, ?, ?, ?, ?)";
		generatePaper(paramList);
		return DBUtil.executeUpdate(Sql, paramList);
	}

	public void generatePaper(List<Object> paramList) {
		String getSingleOptionSql = "SELECT * FROM qes_qestions WHERE question_type=1 AND course_id=? "
				+ "AND difficulty=? " + "ORDER BY RAND() LIMIT ?";
		List<QuestionEntity> singleQuestionEntities = DBUtil.executeQuery(
				QuestionEntity.class, getSingleOptionSql, paramList.get(3),paramList.get(7),
				paramList.get(9));

		String getMultiOptionSql = "SELECT * FROM qes_qestions WHERE question_type=2 AND course_id=? "
				+ "AND difficulty=? " + "ORDER BY RAND() LIMIT ?";
		List<QuestionEntity> multiQquestionEntities = DBUtil.executeQuery(
				QuestionEntity.class, getMultiOptionSql, paramList.get(3),
				paramList.get(10),paramList.get(12));

		String getJudgeSql = "SELECT * FROM qes_qestions WHERE question_type=3 AND course_id=? "
				+ "AND difficulty=? " + "ORDER BY RAND() LIMIT ?";
		List<QuestionEntity> judgeQquestionEntities = DBUtil.executeQuery(
				QuestionEntity.class, getJudgeSql, paramList.get(3),
				paramList.get(13),paramList.get(15));

		// 生成Json文件
		ExamPaperEntity examinationPaperEntity = new ExamPaperEntity();

		examinationPaperEntity.setName((String) paramList.get(0));
		int paperTypeInt = (int) paramList.get(2);
		String paperTypeStr = null;
		if (paperTypeInt == 1) {
			paperTypeStr = "平时测试";
		} else {
			paperTypeStr = "结业考试";
		}
		examinationPaperEntity.setPaperTypeStr(paperTypeStr);
		examinationPaperEntity.setTotalPoint((int) paramList.get(4));
		examinationPaperEntity.setPassPoint((int) paramList.get(5));
		examinationPaperEntity.setTotalMinutes((int) paramList.get(6));
		examinationPaperEntity.setSingleOptionEachPoint((int) paramList.get(8));
		examinationPaperEntity.setMultiOptionEachPoint((int) paramList.get(11));
		examinationPaperEntity.setJudgeEachPoint((int) paramList.get(14));
		examinationPaperEntity.setSingleQuestionEntities(singleQuestionEntities);
		examinationPaperEntity.setMultiQquestionEntities(multiQquestionEntities);
		examinationPaperEntity.setJudgeQquestionEntities(judgeQquestionEntities);

		String examinationPaperJson = FastjsonUtil
				.toJson(examinationPaperEntity);

		String fileName = (String) paramList.get(1);
		File file = new File(fileName);
		if (file.exists() == false) {
			try {
				file.createNewFile();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		FileWriter fwriter = null;
		try {
			fwriter = new FileWriter(fileName);
			fwriter.write(examinationPaperJson);
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				fwriter.flush();
				fwriter.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

	public int updatePaper(List<Object> paramList) {
		StringBuilder sb = new StringBuilder();
		sb.append("UPDATE qes_exam_paper ");
		sb.append(" SET name = ?, paper_type = ?, course_id = ?, total_point = ?, pass_point = ?, total_minutes = ?, single_option_number = ?,single_option_each_point = ?, single_option_difficulty = ?, multi_option_number = ?, multi_option_each_point = ?, multi_option_difficulty = ?,judge_number = ?, judge_each_point = ?, judge_difficulty =?, memo = ? ");
		sb.append(" WHERE id = ? ");
		return DBUtil.executeUpdate(sb.toString(), paramList);
	}

	/**
	 * 试卷信息的模糊查询
	 * 
	 * @param page
	 * @param rows
	 * @param searchName
	 * @param papertypeChoose
	 * @return
	 */
	public PageModel<ExamPaperEntity> search(int page, int rows,
			String searchName, String papertypeChoose) {
		List<Object> paramList = new ArrayList<>();
		StringBuilder sb = new StringBuilder();
		sb.append("SELECT qe.id,qe.name,qe.paper_url,qe.total_point,qe.pass_point,qe.total_minutes,qe.state ");
		sb.append(",co.name AS sys_course_name ");
		sb.append("FROM qes_exam_paper qe,sys_course co ");
		sb.append("WHERE qe.course_id = co.id ");
		if (StringUtils.isNotBlank(searchName)) {
			sb.append("AND qe.name LIKE ? ");
			paramList.add("%" + searchName + "%");
		}
		sb.append(" LIMIT ?,? ");
		paramList.add((page - 1) * rows);
		paramList.add(rows);
		System.out.println(sb.toString());
		for (Object object : paramList) {
			System.out.println(object);
		}
		return DBUtil.executeQueryByPage(ExamPaperEntity.class, sb.toString(),
				paramList);
	}

	/**
	 * 试卷状态修改
	 * 
	 * @param id
	 * @param state
	 * @return
	 */
	public int changeState(String id, String state) {
		String sql = "";
		if ("1".equals(state)) {
			sql = "UPDATE qes_exam_paper SET state = 2 WHERE id=?";
		} else if ("2".equals(state)) {
			sql = "UPDATE qes_exam_paper SET state = 1 WHERE id=?";
		}
		return DBUtil.executeUpdate(sql, id);

	}

	public ExamPaperEntity detailselect(int parseInt) {
		StringBuilder sb = new StringBuilder();
		sb.append("SELECT p.paper_type,  p.paper_url, p.id, p.`name`,c.`name` as 'sys_course_name', p.paper_type, p.course_id, p.total_point, p.pass_point, p.total_minutes, p.single_option_number, p.single_option_each_point, ");
		sb.append("p.single_option_difficulty, p.multi_option_number, p.multi_option_each_point, p.multi_option_difficulty, p.judge_number, p.judge_each_point, p.judge_difficulty, u.`name` as 'sys_user$name', p.opreate_time, p.state, p.memo ");
		sb.append("FROM qes_exam_paper p,sys_course c,sys_user u ");
		sb.append("WHERE p.course_id=c.id AND p.opreate_user_id=u.id AND p.id = ?");
		return DBUtil.getUniqueResult(ExamPaperEntity.class, sb.toString(),
				parseInt);
	}

	// /**
	// * 添加json文件路径到数据库中
	// *
	// * @param paperUrl
	// * @param paperId
	// * @return
	// */
	// public int addPaperUrl(String paperUrl, int paperId) {
	// String sql = "update qes_exam_paper set paper_url=? where id=?";
	// return DBUtil.executeUpdate(sql, paperUrl, paperId);
	// }
	//
	// /**
	// * 根据试卷信息生成符合试卷信息的试卷题目组成的id集合
	// *
	// * @param courseType
	// * @param questionType
	// * @param questionDifficulty
	// * @return List<Integer>
	// */
	// public List<QuestionEntity> getQestions(int questionType, int
	// questionNumber) {
	// String sql = "SELECT * FROM qes_qestions " + "" + "" + "" + "" + ""
	// + " GROUP BY RAND() LIMIT ?";
	// List<QuestionEntity> qestions = DBUtil.executeQuery(
	// QuestionEntity.class, sql, questionType, questionNumber);
	// return qestions;
	// }
}